<template>
  <div class="curRoleNodeBox h100">
    <a-form-model :model="formData" ref="formComp" :rules="rules" class="curRoleNodeBaseInfo commonSelectWidth table-page-search-wrapper">
      <a-row :gutter="[8, 16]">
        <a-col :md="4" :sm="24">
          <a-form-model-item prop="name" label="">
<!--            <span style="position: relative; left: -10px" class="requiredSty"> </span>-->
            <a-input
              v-model="formData.name"
              :placeholder="$t('pleaseInput') + $t('roleName').toLowerCase()"
              :max-length="50"

            />
          </a-form-model-item>
        </a-col>
        <a-col :md="9" :sm="24">
          <a-form-model-item>
            <a-checkbox :checked="formData.enableMessageNotice" @change="changeMessageNotice">{{
              $t('serviceOpenEmail')
            }}</a-checkbox>
            <a-checkbox :checked="formData.auditor === 1" @change="(e) => formData.auditor = e.target.checked ? 1 : 0">{{
              $t('用户注册角色选项')
              }}</a-checkbox>
          </a-form-model-item>
        </a-col>
<!--        <a-col :md="20" :sm="24">-->
<!--          <a-form-model-item prop="remark">-->
<!--            <a-textarea-->
<!--              style="resize: none"-->
<!--              v-model="formData.remark"-->
<!--              :rows="2"-->
<!--              :max-rows="2"-->
<!--              :max-length="200"-->
<!--              :placeholder="$t('pleaseInput') + $t('remark').toLowerCase()"-->
<!--            />-->
<!--          </a-form-model-item>-->
<!--        </a-col>-->
        <a-col :span="24">
          <a-form-model-item prop="" label="">
            <custom-text-area
              @change="formData.remark = $event"
              :val="formData.remark"
              :rows="2"
              :max-len="200"
            ></custom-text-area>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
    <div style="padding-left:37px;padding-bottom:5px">
      <auth-button type="info" :auth="managePerms.role.view" @click="getMenuData" style="margin-right: 10px">刷新</auth-button>
      <template  v-if="roleCheck">
        <span>勾选联动：  </span><a-switch checked-children="开" un-checked-children="关" v-model="checkNonStrictly"/>
        <span v-show="checkNonStrictly" style="padding-left:15px;color:red">注意：打开联动时，子节点全部未勾选会自动把父节点取消勾选，导致和不联动时显示可能不一样</span>
      </template>
    </div>
    <a-spin :spinning="loadingTreeData" class="nodeCheckboxes" style="overflow-y: auto">
<!--      <div class="nodeCheckboxes">-->
<!--      <load-data-spin v-if="loadingTreeData"></load-data-spin>-->
      <a-tree
        checkable
        v-model="usedCheckedKeys"
        :defaultExpandAll="true"
        :check-strictly="!checkNonStrictly"
        :replaceFields="replaceFields"
        :tree-data="treeData"
        v-if="treeData.length"
        @check="onCheck"
      >
        <template slot="title" slot-scope="item">
          {{$t(item.title)}}
        </template>

        <!--        <a-tree-node-->
<!--          class="yijili"-->
<!--          v-for="node in treeData"-->
<!--          :key="node.id"-->
<!--          :code="node.code"-->
<!--          :title="$t(node.title)"-->
<!--        >-->
<!--          <a-tree-node-->
<!--            class="erjili"-->
<!--            v-for="child in node.childMenus"-->
<!--            :key="child.id"-->
<!--            :code="child.code"-->
<!--            :title="$t(child.title)"-->

<!--          >-->
<!--            <a-tree-node-->
<!--              v-for="grandson in child.childMenus"-->
<!--              :title="$t(grandson.title)"-->
<!--              :code="grandson.code"-->
<!--              :key="grandson.id"-->
<!--            />-->
<!--          </a-tree-node>-->
<!--        </a-tree-node>-->
      </a-tree>
<!--    </div>-->
    </a-spin>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import LoadDataSpin from '@/components/LoadDataSpin/Index.vue'
import lodash from 'lodash'
import { checkTextLen } from '@/utils/validate'
import AuthButton from '@/components/AuthButton'
import { managePerms } from '@/config/permission/index'
import CustomTextArea from '@/components/CustomTextArea/index.vue'
const initFormData = {
  id: null,
  name: '',
  remark: '',
  auditor: 0,
  enableMessageNotice: false
}
export default {
  components: {
    LoadDataSpin,
    CustomTextArea,
    AuthButton
  },
  props: {
    action: {
      type: String,
      required: true
    },
    defaultCheckStrictly: {
      type: Boolean,
      default: true
    },
    time: {
      type: Number,
      default: 5647890
    },
    selectedRoleFromU1List: {
      type: [Object],
      default: () => ({ id: '' })
    }
  },
  computed: {
    ...mapState({
      selectedRole: (state) => state.role.selectedRole,
      treeData: (state) => state.menu.menuData
    }),
    treeList(){
      const list = [];
      function findInChildren(children) {
        children.forEach(child => {
          list.push(child);
          if(child.childMenus && child.childMenus.length > 0){
            findInChildren(child.childMenus);
          }
        })
      }
      findInChildren(this.treeData);
      return list;
    },
    usedCheckedKeys : {
      get(){
        if (this.checkNonStrictly) {
          //联动时只勾选叶子节点（按钮）
          return this.treeList.filter((item) => {
            if (!this.checkedKeys.includes(item.id)) {
              return false;
            }
            //叶子节点
            if (!item.childMenus || item.childMenus.length === 0) {
              return true;
            }
            //按钮
            return item.type === 2;
          }).map(item => item.id)
        }
        return this.checkedKeys;
      },
      set(val){

      }
    }
  },
  data () {
    return {
      managePerms,
      checkNonStrictly: !this.defaultCheckStrictly,
      formData: lodash.clone(initFormData),
      expandedKeys: ['0-0'],
      autoExpandParent: true,
      checkedKeys: [],
      copyCheckedKeys: [],
      roleCheck:false,
      replaceFields: {
        title: 'title',
        children: 'childMenus',
        key: 'id',
        label: 'code'
      },
      notChangeFormData: true,
      rules: {
        name: [{ required: true, message: this.$t('pleaseInput') }, { validator: checkTextLen() }],
        remark: [{ validator: checkTextLen(200) }]
      },
      loadingTreeData: false,
      halfCheckedKeys: []
    }
  },
  watch: {
    selectedRole: {
      handler (val) {
        if (this.action === 'add') {
          this.formData = lodash.clone(initFormData)
          this.setCheckedKeys([])
          return
        }
        if (val && val.id) {
          this.getCurRoleMenu()
          this.setFormData(val)
        }
      },
      immediate: true
    },
    time: {
      handler () {
        if (this.action === 'add') {
          this.resetFormData()
          return
        }
        if (this.selectedRole && this.selectedRole.id) {
          this.getCurRoleMenu()
          this.setFormData(this.selectedRole)
        }
      },
      immediate: true
    },
    // 当修改菜单时监听checkkey，避免用户不勾选权限或者趁角色权限没有加载出来的时候多次点击
    checkedKeys: {
      handler (value) {
        if (this.action === 'edit' && Array.isArray(value) && value.length > 0) {
          this.$emit('changeConfirmBtn', false)
        } else {
          this.$emit('changeConfirmBtn', true)
        }
      },
      immediate: true,
      deep: true
    }
  },
  created () {
    this.getMenuData()
  },
  mounted () {
    const vm = this
    window.setRoleCheck = function (show=true) { // 控制角色管理勾选联动开关
    vm.roleCheck=show
    }
  },
  methods: {
    changeMessageNotice (evt) {
      this.formData.enableMessageNotice = evt.target.checked
    },
    getMenuData () {
      // if (this.treeData.length) {
      //   return
      // }
      this.loadingTreeData = true
      this.$store
        .dispatch('getMenuData')
        .then(() => {})
        .finally(() => {
          this.loadingTreeData = false
        })
    },
    getCurRoleMenu () {
      this.checkedKeys = []
      this.copyCheckedKeys = []
      this.$store.dispatch('getRoleMenuData', { ids: [this.selectedRole.id] }).then((data) => {
        this.checkedKeys = data
        this.copyCheckedKeys = [...data]
      })
    },
    getSelectedKeys (data) {
      let arr = []
      data.forEach((item) => {
        arr.push(item.id)
        if (item.childMenus.length) {
          arr = arr.concat(this.getSelectedKeys(item.childMenus))
        }
      })
      return arr
    },
    setFormData (data) {
      this.formData.name = data.name
      this.formData.remark = data.remark
      this.formData.auditor = data.auditor
      this.formData.id = data.id
      this.formData.enableMessageNotice = data.enableMessageNotice
    },
    setCheckedKeys (data) {
      this.checkedKeys = [...data]
    },
    initPageData ({ checkedKeys, notChangeFormData }) {
      this.setCheckedKeys(checkedKeys)
      this.notChangeFormData = notChangeFormData
    },
    onExpand (expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onCheck (checkedKeys, e) {
      // let checkedKeysResult = [...checkedKeys, ...info.halfCheckedKeys];
      //   this.setState({
      //       checkedKeys,
      //       checkedKeysResult
      //   });
      // // 联动会导致数据结构不一样，需要判断
      if (checkedKeys instanceof Array) {
        // 联动check时
        this.checkedKeys = checkedKeys;
        this.halfCheckedKeys = e.halfCheckedKeys;
      } else {
        // 非联动check 时
        this.checkedKeys = checkedKeys.checked; // 此时node.checked值已经变化
        this.halfCheckedKeys = checkedKeys.halfChecked
      }
      this.$nextTick(() => {
        this.controlView(e.node)
      })
    },
    // 其他功能控制查询功能
    controlView (node) {
      if (!node.dataRef.code) return // 如果没有code则退出
      const codeTagArray = node.dataRef.code.split(':')
      const lastCode = codeTagArray.pop() // 去除code数组最后一个元素
      const frontCode = codeTagArray.join(':')
      const codeTag = node.dataRef.remark.includes('测试车辆')?`${frontCode}:testView`:`${frontCode}:view`
      const sameLevel = node.$parent.$children
      if (sameLevel && sameLevel.length) {
        let diableViewTag = false
        sameLevel.forEach((item) => {
          if (lastCode.endsWith('view')||lastCode.endsWith('testView')) {
            // 点击的是查看类按钮 需判断是否勾选其他权限
            // 某些模块包含多个模块 必须判断itemFrontCode === frontCode
            if (!item.dataRef || !item.dataRef.code) return
            const itemCodeTagArray = item.dataRef.code.split(':')
            itemCodeTagArray.pop() // 去除code数组最后一个元素
            const itemFrontCode = itemCodeTagArray.join(':')
            if (codeTag !== item.dataRef.code && itemFrontCode === frontCode && item.checked) {
              diableViewTag = true
            }
          } else {
            // 点击其他按钮 查看按钮需要选中
            if (node.checked && item.dataRef && codeTag === item.dataRef.code) {
              this.checkedKeys.push(item.eventKey)
            }
          }
        })
        // 如果有其他功能权限 查看权限不能取消
        if (diableViewTag) {
          this.checkedKeys.push(node.eventKey)
          this.$message.warning(this.$t('clickViewTip'))
        }
      }
    },
    clearAll () {
      this.checkedKeys = []
      this.copyCheckedKeys = []
      this.setFormData(initFormData)
    },
    // 获取表单中的数据
    getFormData () {
      return new Promise((resolve, reject) => {
        const data = { ...this.formData }
        if (!lodash.isEqual(this.copyCheckedKeys, this.checkedKeys)) {
          data.menuIds = [...this.checkedKeys, ...this.halfCheckedKeys]
        } else {
          delete data.menuIds
        }
        // 如果是新增才判断有没有menuIds，有则说明一定是在空权限的基础上勾选了权限
        if ((!data.id) && (!this.otherCheck(data))) {
          return
        }
        this.$refs.formComp.validate((valid) => {
          if (!valid) {
            reject(valid)
          }
          resolve(data)
        })
      })
    },
    otherCheck (data) {
      // 如果是新增角色必须要有勾选的id
      if (data.menuIds && Array.isArray(data.menuIds) && data.menuIds.length > 0) {
        return true
      }
      this.$message.warning(this.$t('mustChooseOne'))
      return false
    },
    resetFormData () {
      this.formData = lodash.clone(initFormData)
      this.setCheckedKeys([])
    }
  }
}
</script>
<style scoped lang="less">
.curRoleNodeBox {
  display: flex;
  flex-direction: column;
  .curRoleNodeBaseInfo {
    padding: 16px 12px 0px 37px;
  }
  .nodeCheckboxes {
    flex: 1 0 0;
    overflow: auto;
    padding: 0 12px 0 37px;
  }
}
.erjili {
  display: flex;
  align-items: center;
  .ant-tree-child-tree {
    flex: 1 0 0;
    display: flex !important;
    padding-left: 50px;
  }
}
</style>
<style lang="less">
 ::-webkit-scrollbar {
   width: 0 !important;
  //     width: 10px; /*滚动条的宽度*/
  //     height: 8px; /*滚动条的高度*/
    }

.yijili {
  > .ant-tree-child-tree {
    padding: 0 0 0 40px;
  }
}
.erjili {
  > .ant-tree-switcher,
  .ant-tree-switcher_close,
  .ant-tree-switcher_open {
    display: none !important;
  }
  > .ant-tree-node-content-wrapper {
    width: 300px;
    overflow: hidden;
    text-overflow: ellipsis;
    flex: none;
  }
  > .ant-tree-child-tree {
    flex: 1 0 0;
    overflow: auto;
    display: flex !important;
    > li:first-child {
      padding-top: 4px;
    }
  }
}
.curRoleNodeBox{
  .commonSelectWidth{
    margin-bottom: 0;
  }
  .ant-tree li ul{
    max-width: 100%;
    overflow: scroll;
  }
  .ant-tree-child-tree > li:has(> .ant-tree-switcher-noop) {
    color: red;
    display: inline;
    .ant-tree-node-content-wrapper {
      background-color: aliceblue;
    }
  }
}

</style>
